<?php
/**
 * Created by PhpStorm.
 * User: hcz
 * Date: 2017/1/1
 * Time: 19:51
 */
namespace Api\Model\Amazon;
class InboundModel extends  CommonModel {
    /*记录API日志*/
    protected $logModel = NULL;

    public function __construct() {
        $this->logModel = D('Api/Amazon/Log','Model');
        $this->vendorApi('FBAInboundServiceMWS.Client');
        $this->vendorApi('FBAInboundServiceMWS.Exception');

        //parent::__construct();
    }


    /**
     * @param $account
     * @return bool|\FBAInboundServiceMWS_Client
     * 根据账号数组信息获取对应账号站点服务客户端
     */
    private function getService($account){
        if(empty($account) || !is_array($account)) return false;
        $config = array(
            'ServiceURL'    => $account['service_url_shipment'],
            'ProxyHost'     => NULL,
            'ProxyPort'     => -1,
            'ProxyUsername' => null,
            'ProxyPassword' => null,
            'MaxErrorRetry' => 3,
        );

        return new \FBAInboundServiceMWS_Client($account['access_key_id'], $account['secret_key'], 'yks', '1.0', $config);
    }
    /*
     * 描述 : 返回创建入库货件所需信息
     * 参数 :
     *      $accountId : 站点信息,也就是帐号
     *      $options :  数组 {
     *          ShipFromAddress : 邮寄地址信息 数组{
     *              Name                : 名称或公司名称 ,必填,
     *              AddressLine1        : 街道地址信息,必填,
     *              AddressLine2        : 其他街道地址信息（如果需要）,
     *              City                : 城市,必填,
     *              DistrictOrCountry   : 区或县,
     *              StateOrProvinceCode : 省/自治区/直辖市代码,
     *              PostalCode          : 邮政编码,
     *              CountryCode         : 国家地区代码,必填,
     *          }
     *          LabelPrepPreference :  	您对入库货件标签准备的选项设置,可以不填,默认值为SELLER_LABEL,
     *          shipmentPlanItems   : 入库货件中各商品的 SKU 和数量信息 数组 {
     *              数组 {
     *                  SellerSku             : 商品的卖家SKU,必填,
     *                  Quantity              : 商品数量,必填,
     *              },...
     *          }
     *      }
     * 返回 : 用于创建入库货件的入库货件信息
     *      数组 {
     *          ShipmentId : 货件编号,
     *          ShipToAddressId :
     *          ShipFromAddressId :
     *          DestinationFulfillmentCenterId : 您的货件将运至的亚马逊配送中心的编号,
     *          Items : 数组{
     *                      数组 {
     *                      SellerSKU             : 商品的卖家SKU,
     *                      FulfillmentNetworkSKU : 商品的亚马逊配送网络SKU,
     *                      Quantity              : 要配送的商品数量,
     *                  },...
     *           },...
     * 作者：kelvin 2017-01-06
    */
    public function createInboundShipmentPlan($account = null, $options = array()){
        $this->vendorApi('FBAInboundServiceMWS.Model.CreateInboundShipmentPlanRequest');
        $this->vendorApi('FBAInboundServiceMWS.Model.Address');
        $this->vendorApi('FBAInboundServiceMWS.Model.InboundShipmentPlanRequestItem');
        $this->vendorApi('FBAInboundServiceMWS.Model.InboundShipmentPlanRequestItemList');
        if(empty($account['id'])){
            return FALSE;
        }
        $service = $this->getService($account);
        $request = new \FBAInboundServiceMWS_Model_CreateInboundShipmentPlanRequest();
        $request->setSellerId($account['merchant_id']);
        $site_id = D('Api/Amazon/AccountSite','Model')->getSiteIdByAccountId($account['id']);
        $CountryCode = D('Api/Amazon/Sites','Model')->getSiteCodes($site_id);
        $request->setShipToCountryCode($CountryCode);
        $add = new \FBAInboundServiceMWS_Model_Address();
        $request->setShipFromAddress($add->setName($options['ShipFromAddress']['Name']));
        $request->setShipFromAddress($add->setAddressLine1($options['ShipFromAddress']['AddressLine1']));
        $request->setShipFromAddress($add->setAddressLine2($options['ShipFromAddress']['AddressLine2']));
        $request->setShipFromAddress($add->setCity($options['ShipFromAddress']['City']));
        $request->setShipFromAddress($add->setStateOrProvinceCode($options['ShipFromAddress']['StateOrProvinceCode']));
        $request->setShipFromAddress($add->setPostalCode($options['ShipFromAddress']['PostalCode']));
        $request->setShipFromAddress($add->setCountryCode($options['ShipFromAddress']['CountryCode']));
        $request->setLabelPrepPreference($options['LabelPrepPreference']);
        $sku = new \FBAInboundServiceMWS_Model_InboundShipmentPlanRequestItem();
        $member = new \FBAInboundServiceMWS_Model_InboundShipmentPlanRequestItemList();
        foreach($options['shipmentPlanItems'] as $v){
            $sku->setSellerSKU($v['SellerSKU']);
            $sku->setQuantity($v['Quantity']);
            $member->withmember($sku);
            $sku = new $sku;
        }
        $request->setInboundShipmentPlanRequestItems($member);
        try{
            $response = $service->createInboundShipmentPlan($request);
            $this->logModel->apiLog('CreateInboundShipmentPlan',$account,$options,$request,$response);

            $shipmentInfo = array();

            if($response->isSetCreateInboundShipmentPlanResult()){
                $result = $response->getCreateInboundShipmentPlanResult();
                $InboundShipmentPlans = $result->getInboundShipmentPlans();
                if($InboundShipmentPlans->isSetmember()){
                    $members = $InboundShipmentPlans->getmember();
                    foreach ($members as $k => $member){
                        if($member->isSetShipmentId()){
                            $shipmentInfo[$k]['ShipmentId'] = $member->getShipmentId();
                        }
                        if($member->isSetDestinationFulfillmentCenterId()){
                            $shipmentInfo[$k]['DestinationFulfillmentCenterId'] = $member->getDestinationFulfillmentCenterId();
                        }
                        if($member->isSetShipToAddress()){
                             $shipToAddress= $this->formatAddress($member->getShipToAddress());
                             $shipToAddress['CenterId'] = $member->getDestinationFulfillmentCenterId();
                             $shipFromAddress_id = D('Api/Amazon/AccountSite','Service')->getAccountShipFromAddressId($account['id']);
                             $shipToAddress_id = D('Api/Amazon/ShipToAddress','Service')->getOrInsertShipToAddress($account['id'],$shipToAddress);
                             $shipmentInfo[$k]['ship_to_address_id'] = $shipToAddress_id;
                             $shipmentInfo[$k]['ship_from_address_id'] = $shipFromAddress_id;

                        }
                        if($member->isSetItems()){
                            $Items = $member->getItems();

                            if($Items->isSetmember()){
                                $ItemsMembers = $Items->getmember();
                                foreach ($ItemsMembers as $v =>$ItemMember){
                                    if($ItemMember->isSetSellerSKU()){
                                        $shipmentInfo[$k]['Items'][$v]['SellerSKU'] = $ItemMember->getSellerSKU();
                                        /*FulfillmentNetworkSKU是要用来打印条形码的字符串*/
                                        $shipmentInfo[$k]['Items'][$v]['FulfillmentNetworkSKU'] = $ItemMember->getFulfillmentNetworkSKU();

                                        $shipmentInfo[$k]['Items'][$v]['Quantity'] = $ItemMember->getQuantity();

                                    }

                                }
                            }
                        }
                    }
                }
                $this->logModel->apiLog('CreateInboundShipmentPlanResult',$account,$options,$shipmentInfo,time());
                $msg = array(
                    'status' =>200,
                    'msg' => $shipmentInfo
                );
                return $msg;
            }

        } catch (\FBAInboundServiceMWS_Exception $ex) {
            $this->logModel->apiErrorLog('CreateInboundShipmentPlan',$account,$options,$request,$ex);
            $this->error = $ex->getMessage();
            $msg = array(
                'status' =>500,
                'msg' => $this->error
            );
            return $msg;
        }
    }
    /* 描述：创建入库货件
     * 参数：
     *     $accountId : 站点信息,也就是帐号
     *      $options :  数组 {
     *          ShipmentId            : 最初由 CreateInboundShipmentPlan 操作返回的货件编号,必填,
     *          InboundShipmentHeader : 入库货件的标题信息 数组{
     *              ShipmentName : 您为货件选择的名称,请使用命名规则（如货件创建日期）,以帮助您区分不同时间段的货件,必填,
     *              ShipFromAddress : 退货地址 数组{
     *                  Name                : 名称或公司名称 ,必填,
     *                  AddressLine1        : 街道地址信息,必填,
     *                  AddressLine2        : 其他街道地址信息（如果需要）,
     *                  City                : 城市,必填,
     *                  DistrictOrCountry   : 区或县,
     *                  StateOrProvinceCode : 省/自治区/直辖市代码,
     *                  PostalCode          : 邮政编码,
     *                  CountryCode         : 国家地区代码,必填,
     *              },
     *              DestinationFulfillmentCenterId : 亚马逊配送中心标识,必填,
     *              LabelPrepPreference : 入库货件的标签准备首选项,默认SELLER_LABEL,必填,
     *              AreCasesRequired : bool 指明入库货件是否包含原厂包装发货商品,
     *              ShipmentStatus   : 入库货件状态,必填,
     *          }
     *          InboundShipmentItems  : 入库货件中商品的SellerSKU和QuantityShipped信息 数组{
     *              数组{
     *                  SellerSKU : 商品的卖家SKU,
     *                  QuantityShipped : 要配送的商品数量
     *              },...
     *          }
     *      }
     * 返回 : ShipmentId
     * 作者 : kelvin 2017-01-06
     *
    */
    public function createInboundShipment($account,$options = array()){
        $this->vendorApi('FBAInboundServiceMWS.Model.CreateInboundShipmentRequest');
        $this->vendorApi('FBAInboundServiceMWS.Model.Address');
        $this->vendorApi('FBAInboundServiceMWS.Model.InboundShipmentHeader');
        $this->vendorApi('FBAInboundServiceMWS.Model.InboundShipmentItem');
        $this->vendorApi('FBAInboundServiceMWS.Model.InboundShipmentPlanRequestItemList');
        $service = $this->getService($account);
        $request = new \FBAInboundServiceMWS_Model_CreateInboundShipmentRequest();
        $add = new \FBAInboundServiceMWS_Model_Address();
        $head =  new \FBAInboundServiceMWS_Model_InboundShipmentHeader();
        $item =  new \FBAInboundServiceMWS_Model_InboundShipmentItem();
        $member = new \FBAInboundServiceMWS_Model_InboundShipmentPlanRequestItemList();
        $head->setShipFromAddress($add->setName($options['InboundShipmentHeader']['ShipFromAddress']['Name']));
        $head->setShipFromAddress($add->setAddressLine1($options['InboundShipmentHeader']['ShipFromAddress']['AddressLine1']));
        $head->setShipFromAddress($add->setAddressLine2($options['InboundShipmentHeader']['ShipFromAddress']['AddressLine2']));
        $head->setShipFromAddress($add->setCity($options['InboundShipmentHeader']['ShipFromAddress']['City']));
        $head->setShipFromAddress($add->setStateOrProvinceCode($options['InboundShipmentHeader']['ShipFromAddress']['StateOrProvinceCode']));
        $head->setShipFromAddress($add->setPostalCode($options['InboundShipmentHeader']['ShipFromAddress']['PostalCode']));
        $head->setShipFromAddress($add->setCountryCode($options['InboundShipmentHeader']['ShipFromAddress']['CountryCode']));
        $head->setShipmentName($options['InboundShipmentHeader']['ShipmentName']);
        $head->setDestinationFulfillmentCenterId($options['InboundShipmentHeader']['DestinationFulfillmentCenterId']);
        $head->setLabelPrepPreference($options['InboundShipmentHeader']['LabelPrepPreference']);
        $head->setShipmentStatus($options['InboundShipmentHeader']['ShipmentStatus']);
        foreach($options['InboundShipmentItems'] as $v){
            $item->setSellerSKU($v['SellerSKU']);
            $item->setQuantityShipped($v['QuantityShipped']);
            $member->withmember($item);
            $item = new $item;
        }
        $request->setSellerId($account['merchant_id']);
        $request->setShipmentId($options['ShipmentId']);
        $request->setInboundShipmentHeader($head);
        $request->setInboundShipmentItems($member);
        try{
            $response = $service->CreateInboundShipment($request);
            $this->logModel->apiLog('CreateInboundShipment',$account,$options,$request,$response);

            if($response->isSetCreateInboundShipmentResult()){
                $result = $response->getCreateInboundShipmentResult();

                if($result->isSetShipmentId()){
                    $ShipmentId = $result->getShipmentId();
                }
                $msg = array(
                    'status' =>200,
                    'msg' => $ShipmentId
                );
                return $msg;
            }

        }catch (\FBAInboundServiceMWS_Exception $ex) {
            $this->logModel->apiErrorLog('CreateInboundShipment', $account, $options, $request, $ex);
            $this->error = $ex->getMessage();
            $msg = array(
                'status' =>500,
                'msg' => $this->error
            );
            return $msg;
        }
    }

    /* 描述：更新现有入库货件
     * 参数：
     *     $accountId : 站点信息,也就是帐号
     *      $options :  数组 {
     *          ShipmentId            : 最初由 CreateInboundShipmentPlan 操作返回的货件编号,必填,
     *          InboundShipmentHeader : 入库货件的标题信息 数组{
     *              ShipmentName : 您为货件选择的名称,请使用命名规则（如货件创建日期）,以帮助您区分不同时间段的货件,必填,
     *              ShipFromAddress : 退货地址 数组{
     *                  Name                : 名称或公司名称 ,必填,
     *                  AddressLine1        : 街道地址信息,必填,
     *                  AddressLine2        : 其他街道地址信息（如果需要）,
     *                  City                : 城市,必填,
     *                  DistrictOrCountry   : 区或县,
     *                  StateOrProvinceCode : 省/自治区/直辖市代码,
     *                  PostalCode          : 邮政编码,
     *                  CountryCode         : 国家地区代码,必填,
     *              },
     *              DestinationFulfillmentCenterId : 亚马逊配送中心标识,必填,
     *              LabelPrepPreference : 入库货件的标签准备首选项,默认SELLER_LABEL,必填,
     *              AreCasesRequired : bool 指明入库货件是否包含原厂包装发货商品,
     *              ShipmentStatus   : 入库货件状态,必填,
     *          }
     *          InboundShipmentItems  : 入库货件中商品的SellerSKU和QuantityShipped信息 数组{
     *              数组{
     *                  SellerSKU : 商品的卖家SKU,
     *                  QuantityShipped : 要配送的商品数量
     *              },...
     *          }
     *      }
     * 返回 : ShipmentId
     * 作者 : kelvin 2017-01-06
     *
    */
    public function updateInboundShipment($account,$options = array()){
        $this->vendorApi('FBAInboundServiceMWS.Model.UpdateInboundShipmentRequest');
        $this->vendorApi('FBAInboundServiceMWS.Model.Address');
        $this->vendorApi('FBAInboundServiceMWS.Model.InboundShipmentHeader');
        $this->vendorApi('FBAInboundServiceMWS.Model.InboundShipmentItem');
        $this->vendorApi('FBAInboundServiceMWS.Model.InboundShipmentItemList');
        $service = $this->getService($account);
        $request = new \FBAInboundServiceMWS_Model_UpdateInboundShipmentRequest();
        $add = new \FBAInboundServiceMWS_Model_Address();
        $head =  new \FBAInboundServiceMWS_Model_InboundShipmentHeader();
        $item =  new \FBAInboundServiceMWS_Model_InboundShipmentItem();
        $member =  new \FBAInboundServiceMWS_Model_InboundShipmentItemList();
        $request->setSellerId($account['merchant_id']);
        $request->setShipmentId($options['ShipmentId']);
        $head->setShipFromAddress($add->setName($options['InboundShipmentHeader']['ShipFromAddress']['Name']));
        $head->setShipFromAddress($add->setAddressLine1($options['InboundShipmentHeader']['ShipFromAddress']['AddressLine1']));
        $head->setShipFromAddress($add->setAddressLine2($options['InboundShipmentHeader']['ShipFromAddress']['AddressLine2']));
        $head->setShipFromAddress($add->setCity($options['InboundShipmentHeader']['ShipFromAddress']['City']));
        $head->setShipFromAddress($add->setStateOrProvinceCode($options['InboundShipmentHeader']['ShipFromAddress']['StateOrProvinceCode']));
        $head->setShipFromAddress($add->setPostalCode($options['InboundShipmentHeader']['ShipFromAddress']['PostalCode']));
        $head->setShipFromAddress($add->setCountryCode($options['InboundShipmentHeader']['ShipFromAddress']['CountryCode']));
        $head->setShipmentName($options['InboundShipmentHeader']['ShipmentName']);
        $head->setDestinationFulfillmentCenterId($options['InboundShipmentHeader']['DestinationFulfillmentCenterId']);
        $head->setShipmentStatus($options['InboundShipmentHeader']['ShipmentStatus']);
        foreach ($options['InboundShipmentItems'] as $v) {
            $item->setSellerSKU($v['SellerSKU']);
            $item->setQuantityShipped($v['QuantityShipped']);
            $member->withmember($item);
            $item = new $item;
        }
        $request->setSellerId($account['merchant_id']);
        $request->setShipmentId($options['ShipmentId']);
        $request->setInboundShipmentHeader($head);
        $request->setInboundShipmentItems($member);
        try{
            $ShipmentId = array();
            $response = $service->updateInboundShipment($request);
            $this->logModel->apiLog('UpdateInboundShipment',$account,$options,$request,$response);
            if($response->isSetUpdateInboundShipmentResult()){
                $result = $response->getUpdateInboundShipmentResult();
                if($result->isSetShipmentId()){
                    $ShipmentId = $result->getShipmentId();
                }
                return $ShipmentId;
            }
        }catch (\FBAInboundServiceMWS_Exception $ex) {
            $this->logModel->apiErrorLog('UpdateInboundShipment', $account, $options, $request, $ex);
            $this->error = $ex->getMessage();
            $msg = array(
                'status' =>500,
                'msg' => $this->error
            );
            return $msg;
        }
    }

    /* 描述：返回入库货件的当前运输信息
     * 参数：
     *     $accountId : 站点信息,也就是帐号
     *      $options :  数组 {
     *          ShipmentId            : 最初由 CreateInboundShipmentPlan 操作返回的货件编号,必填,
     *      }
     * 返回 :
     *      TransportHeader : 数组{
     *          SellerId     : 亚马逊卖家编号,
     *          ShipmentId   : 最初由 CreateInboundShipmentPlan 操作返回的货件编号,
     *          IsPartnered  : 指明 PutTransportContent 请求是否针对亚马逊合作承运人,
     *          ShipmentType : 在 PutTransportContent 请求中指定承运人货件的类型,
     *      },
     *      TransportResult : 数组{
     *          TransportStatus : 亚马逊合作承运人货件的状态
     *      }
     * 作者 : kelvin 2017-01-06
     *
    */
    public function getTransportContent($account,$options = array()){
        $this->vendorApi('FBAInboundServiceMWS.Model.GetTransportContentRequest');
        $service = $this->getService($account);
        $request = new \FBAInboundServiceMWS_Model_GetTransportContentRequest();
        $request->setSellerId($account['merchant_id']);
        $request->setShipmentId($options['ShipmentId']);
        $TransportContent = array();
        try{
            $response = $service->getTransportContent($request);
            $this->logModel->apiLog('GetTransportContent',$account,$options,$request,$response);
            if($response->isSetGetTransportContentResult()){
                $result = $response->getGetTransportContentResult();
                if($result->isSetTransportContent()){
                    $Content = $result->getTransportContent();
                    if($Content->isSetTransportHeader()){
                        $TransportHeader = $Content->getTransportHeader();
                        if($TransportHeader->isSetSellerId()){
                            $TransportContent['TransportHeader']['SellerId'] = $TransportHeader->getSellerId();
                        }
                        if($TransportHeader->isSetShipmentId()){
                            $TransportContent['TransportHeader']['ShipmentId'] = $TransportHeader->getShipmentId();
                        }
                        if($TransportHeader->isSetIsPartnered()){
                            $TransportContent['TransportHeader']['IsPartnered'] = $TransportHeader->getIsPartnered();
                        }
                        if($TransportHeader->isSetShipmentType()){
                            $TransportContent['TransportHeader']['ShipmentType'] = $TransportHeader->getShipmentType();
                        }
                    }
                    if($Content->isSetTransportDetails()){
                        $TransportDetails = $Content->getTransportDetails();
                        if($TransportDetails->isSetNonPartneredSmallParcelData()){
                            $NonPartneredSmallParcelData = $TransportDetails->getNonPartneredSmallParcelData();
                            if($NonPartneredSmallParcelData->isSetPackageList()){
                                $PackageList = $NonPartneredSmallParcelData->getPackageList();
                                if($PackageList->isSetmember()){
                                    $members = $PackageList->getmember();
                                    foreach($members as $member){
                                        if($member->isSetCarrierName()){
                                            $TransportContent['TransportDetails']['NonPartneredSmallParcelData']
                                            ['PackageList']['member'][]['CarrierName'] = $member->getCarrierName();
                                        }
                                        if($member->isSetTrackingId()){
                                            $TransportContent['TransportDetails']['NonPartneredSmallParcelData']
                                            ['PackageList']['member'][]['TrackingId'] = $member->getTrackingId();
                                        }
                                        if($member->isSetPackageStatus()){
                                            $TransportContent['TransportDetails']['NonPartneredSmallParcelData']
                                            ['PackageList']['member'][]['PackageStatus'] = $member->getPackageStatus();
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if($Content->isSetTransportResult()){
                        $TransportResult = $Content->getTransportResult();
                        if($TransportResult->isSetTransportStatus()){
                            $TransportContent['TransportResult']['TransportStatus'] = $TransportResult->getTransportStatus();
                        }
                        if($TransportResult->isSetErrorCode()){
                            $TransportContent['TransportResult']['ErrorCode'] = $TransportResult->getErrorCode();
                        }
                        if($TransportResult->isSetErrorDescription()){
                            $TransportContent['TransportResult']['ErrorDescription'] = $TransportResult->getErrorDescription();
                        }
                    }
                }
                return $TransportContent;
            }
        }catch (\FBAInboundServiceMWS_Exception $ex) {
            $this->logModel->apiErrorLog('GetTransportContent', $account, $options, $request, $ex);
            $this->error = $ex->getMessage();
//            echo $this->error;
            return FALSE;
        }
    }
    /* 描述：返回用于打印入库货件包裹标签的PDF文档数据
     * 参数：
     *     $accountId : 站点信息,也就是帐号
     *      $options :  数组 {
     *          ShipmentId       : 最初由 CreateInboundShipmentPlan 操作返回的货件编号,必填,
     *          PageType         : 表示打印标签时使用的纸张类型
     *          NumberOfPackages : 指示需要贴标的箱子的数量
     *      }
     * 返回 :
     *      数组{
     *          TransportDocument : 用于打印 PDF文档的数据（格式为Base64编码字符串）,
     *          Checksum          : 用于验证PDF文档数据的Base64编码的MD5哈希值
     *      }
     * 作者 : kelvin 2017-01-06
    */
    public function getPackageLabels($account,$options = array()){
        $this->vendorApi('FBAInboundServiceMWS.Model.GetPackageLabelsRequest');
        $service = $this->getService($account);
        $request = new \FBAInboundServiceMWS_Model_GetPackageLabelsRequest();
        $request->setSellerId($account['merchant_id']);
        $request->setShipmentId($options['ShipmentId']);
        $request->setPageType($options['PageType']);
        $request->setNumberOfPackages($options['NumberOfPackages']);
        try{
            $response = $service->getPackageLabels($request);
            $this->logModel->apiLog('GetPackageLabels',$account,$options,$request,$response);
            $PdfDocumentInfo = array();
            if($response->isSetGetPackageLabelsResult()){
                $result = $response->getGetPackageLabelsResult();
                if($result->isSetTransportDocument()){
                    $TransportDocument = $result->getTransportDocument();
                    if($TransportDocument->isSetPdfDocument()){
                        /*您必须对 Base64 编码字符串进行解码，将其保存为二进制文件（扩展名为 .zip）*/
                        $PdfDocumentInfo['PdfDocument'] = $TransportDocument->getPdfDocument();
                    }
                    if($TransportDocument->isSetChecksum()){
                        $PdfDocumentInfo['Checksum'] = $TransportDocument->getChecksum();
                    }
                }
                $msg = array(
                    'status' =>200,
                    'msg' => $PdfDocumentInfo
                );
                return $msg;
            }
        }catch (\FBAInboundServiceMWS_Exception $ex){
            $this->logModel->apiErrorLog('GetPackageLabels',$account,$options,$request,$ex);
            $this->error = $ex->getMessage();
            $msg = array(
                'status' =>500,
                'msg' => $this->error
            );
            return $msg;
        }

    }

    /* 描述：取消之前确认的使用亚马逊合作承运人配送入库货件的请求
     * 参数：
     *      $accountId : 站点信息,也就是帐号
     *      $options :  数组 {
     *          ShipmentId       : 最初由 CreateInboundShipmentPlan 操作返回的货件编号,必填,
     *      }
     * 返回 :
     *      数组{
     *          TransportStatus  : 亚马逊合作承运人货件的状态,
     *      }
     * 作者 : kelvin 2017-01-06
    */
    public function voidTransportRequest($account,$options = array()){
        $this->vendorApi('FBAInboundServiceMWS.Model.VoidTransportInputRequest');
        $service = $this->getService($account);
        $request = new \FBAInboundServiceMWS_Model_VoidTransportInputRequest();
        $request->setSellerId($account['merchant_id']);
        $request->setShipmentId($options['ShipmentId']);
        $TransportStatus = array();
        try{
            $response = $service->voidTransportRequest($request);
            $this->logModel->apiLog('VoidTransportRequest',$account,$options,$request,$response);
            if($response->isSetGetTransportContentResult()){
                $result = $response->getGetTransportContentResult();
                if($result->isSetTransportResult()){
                    $TransportResult = $result->getTransportResult();
                    if($TransportResult->isSetTransportStatus()){
                        $TransportStatus['TransportStatus'] = $TransportResult->getTransportStatus();
                    }
                }
                return $TransportStatus;
            }
        }catch (\FBAInboundServiceMWS_Exception $ex) {
            $this->logModel->apiErrorLog('VoidTransportRequest', $account, $options, $request, $ex);
            $this->error = $ex->getMessage();
//            echo $this->error;
            return FALSE;
        }
    }
    /* 描述：根据您指定的条件返回入库货件列表
     * 参数：
     *      $accountId : 站点信息,也就是帐号
     *      $options :  数组 {
     *          ShipmentIdList : 数组{
     *              货件编号,...
     *          }
     *          ShipmentStatusList : 数组{
     *              货件状态,...
     *          }
     *      }
     * 返回 :
     *   数组{
     *      数组{
     *          数组{
     *              ShipmentId      : 货件编号
     *              ShipmentName    : 货件名称
     *              ShipFromAddress : 地址 数组{
     *                  Name                : 名称或公司名称
     *                  AddressLine1        : 街道地址信息
     *                  AddressLine2        : 其他街道地址信息（
     *                  City                : 城市,
     *                  StateOrProvinceCode : 省/自治区/直辖市代码,
     *                  PostalCode          : 邮政编码,
     *                  CountryCode         : 国家地区代码
     *              },
     *              DestinationFulfillmentCenterId : 亚马逊配送中心标识,
     *              LabelPrepPreference            : 货件的标签选项,
     *              AreCasesRequired               : 指明入库货件是否包含原厂包装发货商品,
     *              ShipmentStatus                 : 入库货件状态
     *          },...
     *      },...
     *  }
     * 作者 : kelvin 2017-01-06
    */
    public function listInboundShipments($account, $options = array()) {
        $this->vendorApi('FBAInboundServiceMWS.Model.ShipmentIdList');
        $this->vendorApi('FBAInboundServiceMWS.Model.ShipmentStatusList');
        $this->vendorApi('FBAInboundServiceMWS.Model.ListInboundShipmentsRequest');
        $this->vendorApi('FBAInboundServiceMWS.Model.ListInboundShipmentsByNextTokenRequest');
        $request = new \FBAInboundServiceMWS_Model_ListInboundShipmentsRequest();
        $request->setSellerId($account['merchant_id']);
        if(isset($options['ShipmentIdList'])) {
            $shipmentIdList = new \FBAInboundServiceMWS_Model_ShipmentIdList();
            $shipmentIdList->setmember($options['ShipmentIdList']);
            $request->setShipmentIdList($shipmentIdList);
        }
        if(isset($options['ShipmentStatusList'])) {
            $shipmentStatusList = new \FBAInboundServiceMWS_Model_ShipmentStatusList();
            $shipmentStatusList->setmember($options['ShipmentStatusList']);
            $request->setShipmentStatusList($shipmentStatusList);
        }
        $service = $this->getService($account);
        $shipmentsResult = array();
        try{
            $response = $service->listInboundShipments($request);
            $this->logModel->apiLog('ListInboundShipments',$account,$options,$request,$response);
            if($response->isSetListInboundShipmentsResult()) {
                $result = $response->getListInboundShipmentsResult();
                if($result->isSetShipmentData()){
                    $shipmentData = $result->getShipmentData();
                    $shipmentsResult[] = $this->formatListInboundShipmentsData($shipmentData,$account['id']);
                }
                while ($result->isSetNextToken()) {
                    $request = new \FBAInboundServiceMWS_Model_ListInboundShipmentsByNextTokenRequest();
                    $request->setSellerId($account['merchant_id']);
                    $request->setNextToken($result->getNextToken());
                    $response = $service->ListInboundShipmentsByNextToken($request);
                    $this->logModel->apiLog('ListInboundShipmentsByNextToken',$account,$options,$request,$response);
                    $result = $response->getListInboundShipmentsByNextTokenResult();
                    if($result->isSetShipmentData()){
                        $shipmentData = $result->getShipmentData();
                        $shipmentsResult[] = $this->formatListInboundShipmentsData($shipmentData);
                    }
                }
            }
            return $shipmentsResult;
        }catch (\FBAInboundServiceMWS_Exception $ex) {
            $this->logModel->apiErrorLog('ListInboundShipments', $account, $options, $request, $ex);
            $this->error = $ex->getMessage();
//            echo $this->error;
            return FALSE;
        }
    }

    /* 描述：返回指定入库货件的商品列表或在指定时间段内更新的商品列表
     * 参数：
     *      $accountId : 站点信息,也就是帐号
     *      $options :  数组 {
     *          ShipmentId        : 货件编号,如果指定了 ShipmentId，则会忽略 LastUpdatedBefore 和 LastUpdatedAfter,
     *          LastUpdatedAfter  : 选择在指定时间（或之后）最后更新入库货件商品时所使用的日期,格式为ISO8601,必须早于LastUpdatedBefore,
     *          LastUpdatedBefore : 选择于指定时间（或之前）最后更新入库货件商品时所使用的日期,格式为ISO8601,必须晚于LastUpdatedAfter
     *      }
     * 返回 :
     *      数组{
     *          数组{
     *              ShipmentId      : 货件编号
     *              SellerSKU       : 卖家SKU
     *              FulfillmentNetworkSKU : 网络sku,
     *              QuantityShipped       : 要配送的商品数量,
     *              QuantityReceived      : 亚马逊配送中心已接收的商品数量,
     *          },...
     *      }
     * 作者 : kelvin 2017-01-06
    */
    public function listInboundShipmentItems($account,$options = array()){
        $this->vendorApi('FBAInboundServiceMWS.Model.ListInboundShipmentItemsRequest');
        $this->vendorApi('FBAInboundServiceMWS.Model.ListInboundShipmentItemsByNextTokenRequest');
        $service = $this->getService($account);
        $request = new \FBAInboundServiceMWS_Model_ListInboundShipmentItemsRequest();
        $request->setSellerId($account['merchant_id']);
        $request->setShipmentId($options['ShipmentId']);
        $request->setLastUpdatedBefore($options['LastUpdatedBefore']);
        $request->setLastUpdatedAfter($options['LastUpdatedAfter']);
        $shipmentItemsResult = array();
        try{
            $response = $service->listInboundShipmentItems($request);
            $this->logModel->apiLog('ListInboundShipmentItems',$account,$options,$request,$response);
            if($response->isSetListInboundShipmentItemsResult()){
                $result = $response->getListInboundShipmentItemsResult();
                if($result->isSetItemData()){
                    $ItemData = $result->getItemData();
                    $shipmentItemsResult = $this->formatListInboundShipmentItemsData($ItemData);
                }
                while ($result->isSetNextToken()) {
                    $request = new \FBAInboundServiceMWS_Model_ListInboundShipmentItemsByNextTokenRequest();
                    $request->setSellerId($account['merchant_id']);
                    $request->setNextToken($result->getNextToken());
                    $response = $service->ListInboundShipmentItemsByNextToken($request);
                    $this->logModel->apiLog('ListInboundShipmentItemsByNextToken',$account,$options,$request,$response);
                    $result = $response->getListInboundShipmentItemsByNextTokenResult();
                    if($result->isSetItemData()){
                        $shipmentItemData = $result->getItemData();
                        $shipmentItemsResult = array_merge($shipmentItemsResult, $this->formatListInboundShipmentItemsData($shipmentItemData));
                    }
                }
            }
            return $shipmentItemsResult;
        }catch (\FBAInboundServiceMWS_Exception $ex) {
            $this->logModel->apiErrorLog('ListInboundShipmentItems', $account, $options, $request, $ex);
            $this->error = $ex->getMessage();
            echo $this->error;
            return FALSE;
        }
    }

    /* 描述：返回指定入库货件的商品列表或在指定时间段内更新的商品列表
     * 参数：
     *      $accountId : 站点信息,也就是帐号
     * 返回 :
     *     数组{
     *          Status      : 服务运行状态
     *                          GREEN
     *                             服务运行正常。
     *                          GREEN_I
     *                              服务运行正常。将提供附加信息。
     *                          YELLOW
     *                              服务产生的错误率已超出正常水平，或运行过程中性能有所降低。可能提供附加信息。
     *                          RED
     *                              服务不可用，或错误率已远远超出正常水平。可能提供附加信息
     *          Timestamp   : 指明对运行状态进行评估的时间
     *          }
     * 作者 : kelvin 2017-01-06
    */
    public function getServiceStatus($account,$options = array()){
        $this->vendorApi('FBAInboundServiceMWS.Model.GetServiceStatusRequest');
        $service = $this->getService($account);
        $request = new \FBAInboundServiceMWS_Model_GetServiceStatusRequest();
        $request->setSellerId($account['merchant_id']);
        $TransportStatus = array();
        try{
            $response = $service->GetServiceStatus($request);
            $this->logModel->apiLog('GetServiceStatus',$account,$options,$request,$response);

            if($response->isSetGetServiceStatusResult()){
                $result = $response->getGetServiceStatusResult();

                if($result->isSetStatus()){
                    $TransportStatus['Status'] = $result->getStatus();
                }
                if($result->isSetTimestamp()){
                    $TransportStatus['Timestamp'] = $result->getTimestamp();
                }
            }
            return $TransportStatus;
        }catch (\FBAInboundServiceMWS_Exception $ex) {
            $this->logModel->apiErrorLog('VoidTransportRequest', $account, $options, $request, $ex);
            $this->error = $ex->getMessage();
            echo $this->error;
            return FALSE;
        }
    }

    /**
     * @param $shipmentData
     * @return array
     * 规范化ListInboundShipments接口返回数据
     */
    public function formatListInboundShipmentsData ($shipmentData,$accountId) {
        $shipmentsResult = array();

        if($shipmentData->isSetmember()){
            $members = $shipmentData->getmember();

            foreach ($members as $k=>$member){
                $memberShipments = array();
                if($member->isSetShipmentId()){
                    $memberShipments['ShipmentId'] = $member->getShipmentId();
                }
                if($member->isSetShipmentName()){
                    $memberShipments['ShipmentName'] = $member->getShipmentName();
                }
                if($member->isSetShipFromAddress()){
                    $shipFromAddress_id = D('Api/Amazon/AccountSite','Service')->getAccountShipFromAddressId($accountId);
                    $memberShipments['ship_from_address_id'] = $shipFromAddress_id;
                    $memberShipments['ShipFromAddress'] = $this->formatAddress($member->getShipFromAddress());
                }
                if($member->isSetDestinationFulfillmentCenterId()){
                    $memberShipments['DestinationFulfillmentCenterId'] = $member->getDestinationFulfillmentCenterId();
                }
                if($member->isSetShipmentStatus()){
                    $memberShipments['ShipmentStatus'] = $member->getShipmentStatus();
                }
                if($member->isSetLabelPrepType()){
                    $memberShipments['LabelPrepType'] = $member->getLabelPrepType();
                }
                if($member->isSetAreCasesRequired()){
                    $memberShipments['AreCasesRequired'] = $member->getAreCasesRequired();
                }

                $shipmentsResult[] = $memberShipments;
            }
        }

        return $shipmentsResult;
    }

    /**
     * @param $ItemData
     * @return array
     * 规范化ListInboundShipmentItems接口返回数据
     */
    public function formatListInboundShipmentItemsData ($ItemData) {
        $shipmentsResult = array();
        if($ItemData->isSetmember()){
            $members = $ItemData->getmember();
            foreach($members as $member){
                $ItemsResult = array();
                if($member->isSetShipmentId()){
                    $ItemsResult['ShipmentId'] = $member->getShipmentId();
                }
                if($member->isSetSellerSKU()){
                    $ItemsResult['SellerSKU'] = $member->getSellerSKU();
                }
                if($member->isSetFulfillmentNetworkSKU()){
                    $ItemsResult['FulfillmentNetworkSKU'] = $member->getFulfillmentNetworkSKU();
                }
                if($member->isSetQuantityShipped()){
                    $ItemsResult['QuantityShipped'] = $member->getQuantityShipped();
                }
                if($member->isSetQuantityReceived()){
                    $ItemsResult['QuantityReceived'] = $member->getQuantityReceived();
                }
                $shipmentsResult[] = $ItemsResult;
            }
        }
        return $shipmentsResult;
    }

    /**
     * 格式化地址
     * 参数：$address（地址对象）
     * 返回：$addressArr（地址数组）
     */
    public function formatAddress($address){
        $addressArr = array();

        if($address->isSetName()){
            $addressArr['Name'] = $address->getName();
        }
        if($address->isSetAddressLine1()){
            $addressArr['AddressLine1'] = $address->getAddressLine1();
        }
        if($address->isSetAddressLine2()){
            $addressArr['AddressLine2'] = $address->getAddressLine2();
        }
        if($address->isSetDistrictOrCounty()){
            $addressArr['DistrictOrCounty'] = $address->getDistrictOrCounty();
        }
        if($address->isSetCity()){
            $addressArr['City'] = $address->getCity();
        }
        if($address->isSetStateOrProvinceCode()){
            $addressArr['StateOrProvinceCode'] = $address->getStateOrProvinceCode();
        }
        if($address->isSetCountryCode()){
            $addressArr['CountryCode'] = $address->getCountryCode();
        }
        if($address->isSetPostalCode()){
            $addressArr['PostalCode'] = $address->getPostalCode();
        }

        return $addressArr;
    }

}